package com.csc.banking.dao;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;

import com.csc.banking.model.UserAttempts;

public class UserDetailsDaoImpl implements UserDetailsDao{
	@Autowired
	UserAttemptsDao userAttemptsDao;
	private static final int MAX_ATTEMPTS = 3;
	
	public void updateFailAttempts(String username) {
		UserAttempts user = getUserAttempts(username);
		if(user==null){
			if (isUserExists(username)) {
				System.out.println("Not exist add new");
				UserAttempts usernew=new UserAttempts(username,1,new Date());
				userAttemptsDao.persist(usernew);
			}
		}else{			
			if (isUserExists(username)) {
				System.out.println("Update +1 falied");
				userAttemptsDao.updateAttempts(username);
			}
			if (user.getAttempts() + 1 >= MAX_ATTEMPTS) {
				System.out.println("Update Locked");
				userAttemptsDao.updateAccountLocked(username);
				throw new LockedException("User Account is locked!");
			}
		}
		
	}
	public void resetFailAttempts(String username) {
		userAttemptsDao.resetAttempts(username);				
	}

	public UserAttempts getUserAttempts(String username) {
		UserAttempts userAttempts=userAttemptsDao.getUserAttempts(username);
		if(userAttempts!=null)
			return userAttempts;
		return null;
	}
	
	private boolean isUserExists(String username) {
		boolean result = false;
		int count = userAttemptsDao.isUserExistInCustomer(username);
		if (count > 0) {
			result = true;
		}
		return result;
	}

}
